package com.taotao.netty.handler;

import com.alibaba.fastjson2.JSON;

import com.taotao.netty.ImServer;
import com.taotao.netty.command.ChatMessage;
import com.taotao.netty.constant.MessageType;
import com.taotao.netty.domain.Result;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.internal.StringUtil;

/**
 * @className: ChatHandler
 * @author: ZhangYuQi
 * @date: 2025/2/26 下午8:11
 * @Version: 1.0
 * @description:
 */


public class ChatHandler {


    public static void execute(ChannelHandlerContext ctx, TextWebSocketFrame frame) {

        try {
            ChatMessage chat= JSON.parseObject(frame.text(),ChatMessage.class);
            switch (MessageType.match(chat.getType())){
                case PRIVATE -> {
//                    if(StringUtil.isNullOrEmpty(chat.getTarget())){
//                        ctx.channel().writeAndFlush(Result.fail("消息发送失败,目标用户不能为空"));
//                        return;
//                    }
                    Channel channel= ImServer.USERS.get(chat.getTarget());
                    if(channel==null || !channel.isActive()){
                        ctx.channel().writeAndFlush(Result.fail("消息发送失败,目标用户:"+chat.getTarget()+"不在线"));
                    }else{
                        channel.writeAndFlush(Result.success("私聊消息（"+chat.getNickname()+")",chat.getContent()));
                    }
                }
                case GROUP -> ImServer.GROUP.writeAndFlush(Result.success("群聊消息 发送者（"+chat.getNickname()+")",chat.getContent()));
                default -> ctx.channel().writeAndFlush(Result.fail("不支持的消息类型"));
            }
        } catch (Exception e) {
            ctx.channel().writeAndFlush(Result.fail("发送消息格式错误,请检查后重试"));
        }

    }
}
